import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import {BigNumber}  from 'bignumber.js';
import { Toast } 	from 'vant';
Vue.use(Toast);

export default {
	name: 'makeOrder',
	data(){
		return {
			payType:0,			//支付方式  1:支付宝  2:银行卡  3:微信
			showDetail:false,
			iconName:'',		//购买的币种类型
			dialogStatus:0,		//按钮点击状态	1:取消   2:付款
			showBox:false,		//是否显示弹窗
			isSelect:false,		//确认取消弹窗，是否勾选
			dropName:'',		//收款账户
			dropCode:'',		//收款账号
			bankName:'',		//收款银行名称
			orderNum:'',		//已成交单量
			showTimer:'00:00',		//倒计时剩余时间
			orderInfo:{
				allPrice:0,		//总价
				account:0,		//购买币数量
				id:0,			//订单编号
			},
			orderId:'',			//当前页面承担非下单功能，保存订单ID
			from:'',			//来源
			isSell:0,			//是否是出售的订单
			dropAccount:'',		//收款地址
			ETHAccount:'',
			EOSAccount:'',
			ajaxBtn:false,
			logo:'',
			countDownTime:0,		//若是购买订单，则倒计时
			haveMessage:false,	//是否有商家消息
			leftSec:0,			//倒计时剩余时间
			isGetData:false,	//是否拉取到接口信息
			onceDialog:false,
		}
	},
	methods:{
		getRed(){
			//获取小红点数量
			let self = this;
			if(!self.dropName) return
			util.callHandler('getSupplierUnreadMsgCount',{
				supplierName:self.dropName
			},res => {
				self.haveMessage = res.count > 0?true:false;
			})
			setTimeout(()=>{
				self.getRed();
			},3000)
		},
		getOrderInfo(){
			//拉取订单信息
			let _url = this.isSell==1?'/mykey/otc-outmoney-detail':'/otc/inmoney-detail';
			util.fetch(util.ajaxUrl+_url,{
				id:this.orderId
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					this.isGetData = true;
					if(!this.isSell) this.ajaxBtn  = true;
					this.orderInfo.allPrice = res.retData.orderrmb.toFixed(2);		//总价
					this.orderInfo.id = res.retData.id;					//订单编号
					this.dropName = res.retData.outname;				//收款账户
					this.dropCode = res.retData.outaddr;				//收款账号
					this.bankName = res.retData.bank_name;				//收款银行
					this.orderNum = res.retData.finish_order_count;		//已成交单量
					this.orderInfo.account  = res.retData.orderusdt;	//数量
					this.iconName = res.retData.currency_id;
					this.payType  = (res.retData.outtype==3 || res.retData.outtype==4)?3:res.retData.outtype;				//支付方式
					if(this.isSell) this.getSellPackage(this.iconName);
					//判断图标icon
					let otcConfig = util.getStorage('otcConfig');
					if(otcConfig){
						otcConfig = JSON.parse(otcConfig);
						if(otcConfig && otcConfig.currency && otcConfig.currency[this.iconName] && otcConfig.currency[this.iconName].logo){
							this.logo = otcConfig.currency[this.iconName].logo;
						}
					}
					//开始倒计时
					this.leftSec = res.retData.left_time || res.retData.lefttime;
					// this.leftSec = 10;
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				Toast.clear();
				console.log(error)
			})
		},
		timer(){
			setTimeout(this.timer,1000);
			if(!this.isGetData) return
			if(!this.leftSec || this.leftSec <= 0){
				this.showTimer = '00:00';
				this.$router.replace({
					path:'/orderDetail',
					query:{
						death:1,
						id:this.orderId,
						pageState:this.isSell?2:1
					}
				})
			}else{
				let mins    = Math.floor(this.leftSec/60);          //分钟
                let seconds = this.leftSec - mins*60;               //秒
                //确保时分秒都是2位数
                mins        = mins.toString().length==1?'0'+mins:mins;
                seconds     = seconds.toString().length==1?'0'+seconds:seconds;
                this.showTimer = mins+':'+seconds;
                this.leftSec = this.leftSec - 1;
			}
		},
		resetLeftSec(){
			//矫正倒计时时间
			let _url = this.isSell==1?'/mykey/otc-outmoney-detail':'/otc/inmoney-detail';
			util.fetch(util.ajaxUrl+_url,{
				id:this.orderId
			}).then(res => {
				if(res.retCode === 0){
					this.leftSec = res.retData.left_time || res.retData.lefttime;
					if(this.leftSec && this.leftSec > 10) setTimeout(this.resetLeftSec,10000);
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				Toast.clear();
				console.log(error)
			})
		},
		upload(status){
			// status  0:取消订单   1:确认订单
			if(status===0 && !this.isSelect) return
			this.dialogStatus = 0;
			this.showBox = false;
			Toast.loading({
 				message: '加载中...',
  				forbidClick: true,
  				duration:10000
			});
			let _url = status===0?'/otc/cancel-inmoney':'/otc/confirm-inmoney';
			util.fetch(util.ajaxUrl+_url,{
				token:util.getToken(),
				id:this.orderInfo.id
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					Toast.clear();
					Toast.success(res.retMsg)
					setTimeout(()=>{
						if(this.orderId && this.from == 'orderList'){
							//订单详情页过来的情况
							util.setStorage('orderId',this.orderId)
							this.goBack('special');
							return
						}
						if(status == 0){
							//取消订单
							this.goBack('special');
							return
						}
						this.$router.replace({
							path:'/orderDetail',
							query:{
								id:this.orderInfo.id,
								pageState:1,
								death:1
							}
						})
					},1500)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		changeOrderStatus(state){
			//修改订单状态
			Toast.loading({
				message: '加载中...',
				duration:0,
				forbidClick: true
			});
			util.fetch(`${util.ajaxUrl}/mykey/otc-outmoeny-state`,{
				token:util.getToken(),
				id:this.orderInfo.id,
				state:state
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					this.$router.replace({
						path:'/orderDetail',
						query:{
							death:1,
							id:this.orderInfo.id,
							pageState:2
						}
					})
					// console.log(res)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				Toast.clear();
				console.log(error)
			})
		},
		showDialog(num){
			//是否显示弹窗
			this.showBox = !this.showBox;
			this.isSelect = this.isSell == 1?true:false;
			if(num) this.dialogStatus = num;
		},
		selectCancel(){
			//取消弹窗页面，是否勾选
			this.isSelect = !this.isSelect;
		},
		isOrderDetail(){
			//是否显示订单详情
			if(this.isSell == 1) return
			this.showDetail = !this.showDetail
		},
		goBack(special){
			util.navigateBack(-1,this,special)
		},
		copyText(target){
			//复制总价
			this.$copyText(target).then(() => {
				Toast('复制成功')
			}).catch(() => {
				Toast('复制失败')
			})
		},
		goContact(){
			if(this.version < 410){
				this.updateDialog();
				// Toast('请升级至最新版本后使用该功能'+this.version)
				return
			}
			// console.log('bbjApp://contractSupplier?orderId='+ this.orderId +'&supplierName='+this.dropName+'&orderType=1')
			util.callHandler('openUrl',{
				url:'bbjApp://contractSupplier?orderId='+ this.orderId +'&supplierName='+this.dropName+'&orderType=1&payType='+this.payType,
				title:'联系商家',
				needLogin:true,
				popVC:false,		//跳转的时候是否干掉当前页面
				hiddenNav:true,		//是否全屏
			},res => {
				console.log(res)
			})
		},
		service(){
			util.callHandler('openUrl',{
				url:'bbjApp://servicerinfo',
				title:'联系客服',
				needLogin:true,
				popVC:false,		//跳转的时候是否干掉当前页面
				hiddenNav:true,		//是否全屏
			},res => {
				console.log(res)
			})
		},
		getSellPackage(iconName){
			//获取转币地址
			util.fetch(`${util.ajaxUrl}/mykey/get-addr`,{
				token:this.token || util.getToken()
			}).then(res => {
				if(res.retCode === 0){
					this.ajaxBtn = true;
					this.dropAccount = res.retData[0][iconName];
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		grayCountDown(){
			this.countDownTime--;
			if(this.countDownTime > 0){
				setTimeout(() => {
					this.grayCountDown();
				},1000)
			}
		},
	},
	created() {
		Toast.loading({
			message: '加载中...',
			duration:0,
			forbidClick: true
		});
		this.getRed();
		this.timer();
		setTimeout(this.resetLeftSec,8000);
		util.waitSDKReady().then(token => {
			let _query = this.$route.query;
			if(_query.orderId){
				this.token = token;
				this.orderId = _query.orderId;
				this.from    = _query.from;
				this.ETHAccount = util.getStorage('ETHAccount');
				this.EOSAccount = util.getStorage('EOSAccount');
				if(this.from && this.from == 'orderList' && !_query.noSession) sessionStorage.setItem('pageState',2)
				if(_query.isSell){
					this.isSell = _query.isSell;
					this.showDetail = true;
				}
				this.getOrderInfo();
			}else{
				Toast('获取数据有误，请返回重试')
			}
		}).catch((e) => {
			Toast('获取token失败')
		})
		setTimeout(() => {
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				// window.location.reload();
				if(this.token) this.getOrderInfo();
				util.callHandler('setStatusBarStyle',{
					style:'dark'
				})
			})
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
		},500)
    }
}